<template>
  <div class="change-request-management">
    <div class="page-header">
      <h1>变更申请管理</h1>
      <p>管理停车场运营商提交的各类变更申请</p>
    </div>

    <!-- 操作区域 -->
    <div class="operation-bar">
      <div class="search-area">
        <el-input v-model="searchForm.parking_lot_name" placeholder="请输入停车场名称搜索" style="width: 300px" clearable
          @keyup.enter="handleSearch" @clear="handleSearch">
          <template #prefix>
            <el-icon>
              <Search />
            </el-icon>
          </template>
        </el-input>

        <el-select v-model="searchForm.status" placeholder="选择状态" style="width: 150px; margin-left: 10px" clearable
          @change="handleSearch">
          <el-option label="待处理" value="pending" />
          <el-option label="已批准" value="approved" />
          <el-option label="已拒绝" value="rejected" />
        </el-select>

        <el-select v-model="searchForm.request_type" placeholder="申请类型" style="width: 150px; margin-left: 10px"
          clearable @change="handleSearch">
          <el-option label="停用申请" value="close_dates" />
          <el-option label="启用申请" value="activate" />
          <el-option label="停车场信息编辑" value="modify_comprehensive" />
          <el-option label="修改车位数" value="modify_spaces" />
          <el-option label="修改图片" value="modify_images" />
          <el-option label="修改信息" value="modify_info" />
        </el-select>

        <el-button type="primary" @click="handleSearch" :loading="loading">
          <el-icon>
            <Search />
          </el-icon>
          搜索
        </el-button>
      </div>
    </div>

    <!-- 数据表格 -->
    <el-card class="table-card">
      <el-table :data="tableData" :loading="loading" stripe style="width: 100%">
        <el-table-column prop="id" label="申请ID" width="80" />

        <el-table-column prop="parking_lot_name" label="停车场名称" min-width="150" show-overflow-tooltip />

        <el-table-column prop="request_type" label="申请类型" width="120">
          <template #default="{ row }">
            <el-tag :type="getRequestTypeTagType(row.request_type)" size="small">
              {{ getRequestTypeText(row.request_type) }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="applicant_name" label="申请人" width="120">
          <template #default="{ row }">
            <div>{{ row.applicant_name || '未知' }}</div>
            <div class="text-gray text-xs">{{ row.applicant_phone || '' }}</div>
          </template>
        </el-table-column>

        <el-table-column prop="reason" label="申请原因" min-width="200" show-overflow-tooltip />

        <el-table-column prop="status" label="状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="getStatusTagType(row.status)" size="small">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="created_at" label="申请时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.created_at) }}
          </template>
        </el-table-column>

        <el-table-column label="操作" width="280" fixed="right">
          <template #default="{ row }">
            <div class="action-buttons">
              <el-button type="primary" size="small" @click="handleView(row)">
                <el-icon>
                  <View />
                </el-icon>
                查看
              </el-button>
              <el-button v-if="row.status === 'pending'" type="success" size="small" @click="handleApprove(row)">
                <el-icon>
                  <Check />
                </el-icon>
                批准
              </el-button>
              <el-button v-if="row.status === 'pending'" type="danger" size="small" @click="handleReject(row)">
                <el-icon>
                  <Close />
                </el-icon>
                拒绝
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination v-model:current-page="pagination.page" v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]" :total="pagination.total" layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </div>
    </el-card>

    <!-- 查看申请详情对话框 -->
    <el-dialog v-model="detailDialogVisible" :title="`申请详情 - ${currentRequest?.parking_lot_name || ''}`" width="800px"
      :close-on-click-modal="false">
      <div v-if="currentRequest" class="request-detail">
        <!-- 基本信息 -->
        <div class="detail-section">
          <h3>基本信息</h3>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="申请ID">{{ currentRequest.id }}</el-descriptions-item>
            <el-descriptions-item label="申请类型">
              <el-tag :type="getRequestTypeTagType(currentRequest.request_type)" size="small">
                {{ getRequestTypeText(currentRequest.request_type) }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="申请人">{{ currentRequest.applicant_name || '未知' }}</el-descriptions-item>
            <el-descriptions-item label="联系电话">{{ currentRequest.applicant_phone || '无' }}</el-descriptions-item>
            <el-descriptions-item label="申请时间">{{ formatDate(currentRequest.created_at) }}</el-descriptions-item>
            <el-descriptions-item label="状态">
              <el-tag :type="getStatusTagType(currentRequest.status)" size="small">
                {{ getStatusText(currentRequest.status) }}
              </el-tag>
            </el-descriptions-item>
          </el-descriptions>
        </div>

        <!-- 申请原因 -->
        <div class="detail-section">
          <h3>申请原因</h3>
          <div class="reason-content">
            {{ currentRequest.reason || '无' }}
          </div>
        </div>

        <!-- 变更内容 -->
        <div class="detail-section">
          <h3>变更内容</h3>
          <div class="change-content">
            <!-- 关闭日期申请 -->
            <div v-if="currentRequest.request_type === 'close_dates'">
              <h4>申请关闭日期：</h4>
              <el-table :data="currentRequest.request_data.closed_dates || []" border>
                <el-table-column prop="date" label="关闭日期" width="150" />
                <el-table-column prop="reason" label="关闭原因" />
              </el-table>
            </div>

            <!-- 车位数修改申请 -->
            <div v-else-if="currentRequest.request_type === 'modify_spaces'">
              <el-descriptions :column="2" border>
                <el-descriptions-item label="当前车位数">
                  {{ currentRequest.current_data?.total_spaces || 0 }}
                </el-descriptions-item>
                <el-descriptions-item label="申请修改为">
                  {{ currentRequest.request_data?.total_spaces || 0 }}
                </el-descriptions-item>
              </el-descriptions>
            </div>

            <!-- 图片修改申请 -->
            <div v-else-if="currentRequest.request_type === 'modify_images'">
              <div class="image-comparison">
                <div class="current-images">
                  <h4>当前图片：</h4>
                  <div class="image-grid">
                    <el-image v-for="(url, index) in (currentRequest.current_data?.image_urls || [])"
                      :key="`current_${index}`" :src="getImageUrl(url)"
                      :preview-src-list="(currentRequest.current_data?.image_urls || []).map(getImageUrl)" fit="cover"
                      style="width: 100px; height: 100px; margin: 5px;" />
                  </div>
                </div>
                <div class="new-images">
                  <h4>申请修改为：</h4>
                  <div class="image-grid">
                    <el-image v-for="(url, index) in (currentRequest.request_data?.image_urls || [])"
                      :key="`new_${index}`" :src="getImageUrl(url)"
                      :preview-src-list="(currentRequest.request_data?.image_urls || []).map(getImageUrl)" fit="cover"
                      style="width: 100px; height: 100px; margin: 5px;" />
                  </div>
                </div>
              </div>
            </div>

            <!-- 基本信息修改申请 -->
            <div v-else-if="currentRequest.request_type === 'modify_info'">
              <el-descriptions :column="1" border>
                <el-descriptions-item v-if="currentRequest.request_data?.name" label="停车场名称">
                  <div class="change-item">
                    <span class="old-value">{{ currentRequest.current_data?.name || '无' }}</span>
                    <el-icon class="arrow-icon">
                      <ArrowRight />
                    </el-icon>
                    <span class="new-value">{{ currentRequest.request_data.name }}</span>
                  </div>
                </el-descriptions-item>
                <el-descriptions-item v-if="currentRequest.request_data?.contact_phone" label="联系电话">
                  <div class="change-item">
                    <span class="old-value">{{ currentRequest.current_data?.contact_phone || '无' }}</span>
                    <el-icon class="arrow-icon">
                      <ArrowRight />
                    </el-icon>
                    <span class="new-value">{{ currentRequest.request_data.contact_phone }}</span>
                  </div>
                </el-descriptions-item>
                <el-descriptions-item v-if="currentRequest.request_data?.description" label="描述信息">
                  <div class="change-item">
                    <div class="old-value">{{ currentRequest.current_data?.description || '无' }}</div>
                    <el-icon class="arrow-icon">
                      <ArrowRight />
                    </el-icon>
                    <div class="new-value">{{ currentRequest.request_data.description }}</div>
                  </div>
                </el-descriptions-item>
              </el-descriptions>
            </div>

            <!-- 统一编辑申请 -->
            <div v-else-if="currentRequest.request_type === 'modify_comprehensive'">
              <div class="comprehensive-changes">
                <!-- 基本信息变更 -->
                <div v-if="hasBasicInfoChanges(currentRequest)" class="change-section">
                  <h4>基本信息变更</h4>
                  <el-descriptions :column="1" border>
                    <el-descriptions-item v-if="hasFieldChange(currentRequest, 'name')" label="停车场名称">
                      <div class="change-item">
                        <span class="old-value">{{ currentRequest.current_data?.name || '无' }}</span>
                        <el-icon class="arrow-icon">
                          <ArrowRight />
                        </el-icon>
                        <span class="new-value">{{ currentRequest.request_data.name }}</span>
                      </div>
                    </el-descriptions-item>
                    <el-descriptions-item v-if="hasFieldChange(currentRequest, 'contact_phone')" label="联系电话">
                      <div class="change-item">
                        <span class="old-value">{{ currentRequest.current_data?.contact_phone || '无' }}</span>
                        <el-icon class="arrow-icon">
                          <ArrowRight />
                        </el-icon>
                        <span class="new-value">{{ currentRequest.request_data.contact_phone }}</span>
                      </div>
                    </el-descriptions-item>
                    <el-descriptions-item v-if="hasFieldChange(currentRequest, 'address')" label="详细地址">
                      <div class="change-item">
                        <span class="old-value">{{ currentRequest.current_data?.address || '无' }}</span>
                        <el-icon class="arrow-icon">
                          <ArrowRight />
                        </el-icon>
                        <span class="new-value">{{ currentRequest.request_data.address }}</span>
                      </div>
                    </el-descriptions-item>
                    <el-descriptions-item v-if="hasFieldChange(currentRequest, 'backup_phone')" label="备用电话">
                      <div class="change-item">
                        <span class="old-value">{{ currentRequest.current_data?.backup_phone || '无' }}</span>
                        <el-icon class="arrow-icon">
                          <ArrowRight />
                        </el-icon>
                        <span class="new-value">{{ currentRequest.request_data.backup_phone }}</span>
                      </div>
                    </el-descriptions-item>
                    <el-descriptions-item v-if="hasFieldChange(currentRequest, 'description')" label="描述信息">
                      <div class="change-item">
                        <div class="old-value">{{ currentRequest.current_data?.description || '无' }}</div>
                        <el-icon class="arrow-icon">
                          <ArrowRight />
                        </el-icon>
                        <div class="new-value">{{ currentRequest.request_data.description }}</div>
                      </div>
                    </el-descriptions-item>
                  </el-descriptions>
                </div>

                <!-- 距离信息变更 -->
                <div v-if="hasDistanceInfoChanges(currentRequest)" class="change-section">
                  <h4>距离信息变更</h4>
                  <el-descriptions :column="1" border>
                    <el-descriptions-item v-if="hasFieldChange(currentRequest, 'airport_distance_km')" label="机场距离">
                      <div class="change-item">
                        <span class="old-value">{{ currentRequest.current_data?.airport_distance_km || 0 }}km</span>
                        <el-icon class="arrow-icon">
                          <ArrowRight />
                        </el-icon>
                        <span class="new-value">{{ currentRequest.request_data.airport_distance_km }}km</span>
                      </div>
                    </el-descriptions-item>
                    <el-descriptions-item v-if="hasFieldChange(currentRequest, 'station_distance_km')" label="高铁站距离">
                      <div class="change-item">
                        <span class="old-value">{{ currentRequest.current_data?.station_distance_km || 0 }}km</span>
                        <el-icon class="arrow-icon">
                          <ArrowRight />
                        </el-icon>
                        <span class="new-value">{{ currentRequest.request_data.station_distance_km }}km</span>
                      </div>
                    </el-descriptions-item>
                    <el-descriptions-item v-if="hasFieldChange(currentRequest, 'shuttle_time_minutes')" label="摆渡时间">
                      <div class="change-item">
                        <span class="old-value">{{ currentRequest.current_data?.shuttle_time_minutes || 0 }}分钟</span>
                        <el-icon class="arrow-icon">
                          <ArrowRight />
                        </el-icon>
                        <span class="new-value">{{ currentRequest.request_data.shuttle_time_minutes }}分钟</span>
                      </div>
                    </el-descriptions-item>
                  </el-descriptions>
                </div>

                <!-- 分类变更 -->
                <div v-if="hasFieldChange(currentRequest, 'category_id')" class="change-section">
                  <h4>分类变更</h4>
                  <el-descriptions :column="1" border>
                    <el-descriptions-item label="停车场分类">
                      <div class="change-item">
                        <span class="old-value">{{ getCategoryName(currentRequest.current_data?.category_id) }}</span>
                        <el-icon class="arrow-icon">
                          <ArrowRight />
                        </el-icon>
                        <span class="new-value">{{ getCategoryName(currentRequest.request_data?.category_id) }}</span>
                      </div>
                    </el-descriptions-item>
                  </el-descriptions>
                </div>

                <!-- 服务设施变更 -->
                <div v-if="hasServiceFacilitiesChanges(currentRequest)" class="change-section">
                  <h4>服务设施变更</h4>
                  <div class="facilities-comparison">
                    <div class="old-facilities">
                      <h5>原有设施：</h5>
                      <div class="facility-tags">
                        <el-tag
                          v-for="facility in getFacilityNames(currentRequest.current_data?.service_facilities || [])"
                          :key="'old_' + facility"
                          size="small"
                          type="info"
                          style="margin: 2px;"
                        >
                          {{ facility }}
                        </el-tag>
                        <span v-if="(currentRequest.current_data?.service_facilities || []).length === 0" class="no-facilities">无</span>
                      </div>
                    </div>
                    <div class="new-facilities">
                      <h5>更新后：</h5>
                      <div class="facility-tags">
                        <el-tag
                          v-for="facility in getFacilityNames(currentRequest.request_data?.service_facilities || [])"
                          :key="'new_' + facility"
                          size="small"
                          type="success"
                          style="margin: 2px;"
                        >
                          {{ facility }}
                        </el-tag>
                        <span v-if="(currentRequest.request_data?.service_facilities || []).length === 0" class="no-facilities">无</span>
                      </div>
                    </div>
                  </div>
                </div>

                <!-- 车位数变更 -->
                <div v-if="hasFieldChange(currentRequest, 'total_spaces')" class="change-section">
                  <h4>车位数变更</h4>
                  <el-descriptions :column="2" border>
                    <el-descriptions-item label="当前车位数">
                      {{ currentRequest.current_data?.total_spaces || 0 }}
                    </el-descriptions-item>
                    <el-descriptions-item label="申请修改为">
                      {{ currentRequest.request_data?.total_spaces || 0 }}
                    </el-descriptions-item>
                  </el-descriptions>
                </div>

                <!-- 价格规则变更 -->
                <div v-if="hasPriceRulesChanges(currentRequest)" class="change-section">
                  <h4>价格规则变更</h4>
                  <div class="price-rules-comparison">
                    <div class="old-price-rules">
                      <h5>原价格规则：</h5>
                      <div class="price-rules-display">
                        {{ formatPriceRules(currentRequest.current_data?.price_rules) }}
                      </div>
                    </div>
                    <div class="arrow-separator">
                      <el-icon class="arrow-icon">
                        <ArrowRight />
                      </el-icon>
                    </div>
                    <div class="new-price-rules">
                      <h5>新价格规则：</h5>
                      <div class="price-rules-display">
                        {{ formatPriceRules(currentRequest.request_data?.price_rules) }}
                      </div>
                    </div>
                  </div>
                  
                  <!-- 详细价格对比 -->
                  <div class="detailed-price-comparison">
                    <el-descriptions :column="1" border>
                      <el-descriptions-item label="计费模式">
                        <div class="change-item">
                          <span class="old-value">{{ getPricingModeText(currentRequest.current_data?.price_rules?.type) }}</span>
                          <el-icon class="arrow-icon">
                            <ArrowRight />
                          </el-icon>
                          <span class="new-value">{{ getPricingModeText(currentRequest.request_data?.price_rules?.type) }}</span>
                        </div>
                      </el-descriptions-item>
                      <el-descriptions-item label="室内外分别定价">
                        <div class="change-item">
                          <span class="old-value">{{ currentRequest.current_data?.price_rules?.indoor_outdoor_enabled ? '启用' : '未启用' }}</span>
                          <el-icon class="arrow-icon">
                            <ArrowRight />
                          </el-icon>
                          <span class="new-value">{{ currentRequest.request_data?.price_rules?.indoor_outdoor_enabled ? '启用' : '未启用' }}</span>
                        </div>
                      </el-descriptions-item>
                    </el-descriptions>
                    
                    <!-- 累计价格对比 -->
                    <div class="daily-prices-comparison">
                      <h6>1-7天累计价格对比：</h6>
                      <el-table :data="getDailyPricesComparison(currentRequest)" border size="small">
                        <el-table-column prop="day" label="天数" width="80" align="center" />
                        <el-table-column prop="oldPrice" label="原价格" width="120" align="center">
                          <template #default="{ row }">
                            <span>{{ row.oldPrice }}元</span>
                          </template>
                        </el-table-column>
                        <el-table-column prop="newPrice" label="新价格" width="120" align="center">
                          <template #default="{ row }">
                            <span>{{ row.newPrice }}元</span>
                          </template>
                        </el-table-column>
                        <el-table-column prop="change" label="变化" align="center">
                          <template #default="{ row }">
                            <span :class="row.changeClass">{{ row.change }}</span>
                          </template>
                        </el-table-column>
                      </el-table>
                    </div>
                    
                    <!-- 第8天起价格对比 -->
                    <el-descriptions :column="1" border style="margin-top: 16px;">
                      <el-descriptions-item label="第8天起每日价格">
                        <div class="change-item">
                          <span class="old-value">{{ currentRequest.current_data?.price_rules?.daily_price_after_7 || 0 }}元/天</span>
                          <el-icon class="arrow-icon">
                            <ArrowRight />
                          </el-icon>
                          <span class="new-value">{{ currentRequest.request_data?.price_rules?.daily_price_after_7 || 0 }}元/天</span>
                        </div>
                      </el-descriptions-item>
                    </el-descriptions>
                  </div>
                </div>

                <!-- 营业资料变更 -->
                <div v-if="hasBusinessDocumentsChanges(currentRequest)" class="change-section">
                  <h4>营业资料变更</h4>
                  
                  <!-- 营业执照 -->
                  <div class="business-document-section">
                    <h5>营业执照：</h5>
                    <div class="document-comparison">
                      <div class="old-documents">
                        <h6>原文件：</h6>
                        <div v-if="currentRequest.current_data?.business_documents?.business_license">
                          <div class="document-item">
                            <span class="document-name">{{ currentRequest.current_data.business_documents.business_license.filename }}</span>
                            <el-button size="small" type="primary" @click="previewDocument(currentRequest.current_data.business_documents.business_license.url)">
                              查看
                            </el-button>
                          </div>
                        </div>
                        <div v-else class="no-documents">无</div>
                      </div>
                      <div class="arrow-separator">
                        <el-icon class="arrow-icon">
                          <ArrowRight />
                        </el-icon>
                      </div>
                      <div class="new-documents">
                        <h6>新文件：</h6>
                        <div v-if="currentRequest.request_data?.business_documents?.business_license">
                          <div class="document-item">
                            <span class="document-name">{{ currentRequest.request_data.business_documents.business_license.filename }}</span>
                            <el-button size="small" type="primary" @click="previewDocument(currentRequest.request_data.business_documents.business_license.url)">
                              查看
                            </el-button>
                          </div>
                        </div>
                        <div v-else class="no-documents">无</div>
                      </div>
                    </div>
                  </div>

                  <!-- 法人身份证 -->
                  <div class="business-document-section">
                    <h5>法人身份证：</h5>
                    <div class="document-comparison">
                      <div class="old-documents">
                        <h6>原文件：</h6>
                        <div v-if="currentRequest.current_data?.business_documents?.legal_id?.length > 0">
                          <div 
                            v-for="(doc, index) in currentRequest.current_data.business_documents.legal_id" 
                            :key="'old_legal_' + index"
                            class="document-item"
                          >
                            <span class="document-name">{{ doc.filename }}</span>
                            <el-button size="small" type="primary" @click="previewDocument(doc.url)">
                              查看
                            </el-button>
                          </div>
                        </div>
                        <div v-else class="no-documents">无</div>
                      </div>
                      <div class="arrow-separator">
                        <el-icon class="arrow-icon">
                          <ArrowRight />
                        </el-icon>
                      </div>
                      <div class="new-documents">
                        <h6>新文件：</h6>
                        <div v-if="currentRequest.request_data?.business_documents?.legal_id?.length > 0">
                          <div 
                            v-for="(doc, index) in currentRequest.request_data.business_documents.legal_id" 
                            :key="'new_legal_' + index"
                            class="document-item"
                          >
                            <span class="document-name">{{ doc.filename }}</span>
                            <el-button size="small" type="primary" @click="previewDocument(doc.url)">
                              查看
                            </el-button>
                          </div>
                        </div>
                        <div v-else class="no-documents">无</div>
                      </div>
                    </div>
                  </div>

                  <!-- 场地租赁合同 -->
                  <div class="business-document-section">
                    <h5>场地租赁合同：</h5>
                    <div class="document-comparison">
                      <div class="old-documents">
                        <h6>原文件：</h6>
                        <div v-if="currentRequest.current_data?.business_documents?.lease_contract?.length > 0">
                          <div 
                            v-for="(doc, index) in currentRequest.current_data.business_documents.lease_contract" 
                            :key="'old_lease_' + index"
                            class="document-item"
                          >
                            <span class="document-name">{{ doc.filename }}</span>
                            <el-button size="small" type="primary" @click="previewDocument(doc.url)">
                              查看
                            </el-button>
                          </div>
                        </div>
                        <div v-else class="no-documents">无</div>
                      </div>
                      <div class="arrow-separator">
                        <el-icon class="arrow-icon">
                          <ArrowRight />
                        </el-icon>
                      </div>
                      <div class="new-documents">
                        <h6>新文件：</h6>
                        <div v-if="currentRequest.request_data?.business_documents?.lease_contract?.length > 0">
                          <div 
                            v-for="(doc, index) in currentRequest.request_data.business_documents.lease_contract" 
                            :key="'new_lease_' + index"
                            class="document-item"
                          >
                            <span class="document-name">{{ doc.filename }}</span>
                            <el-button size="small" type="primary" @click="previewDocument(doc.url)">
                              查看
                            </el-button>
                          </div>
                        </div>
                        <div v-else class="no-documents">无</div>
                      </div>
                    </div>
                  </div>
                </div>

                <!-- 图片变更 -->
                <div v-if="hasImageChanges(currentRequest)" class="change-section">
                  <h4>图片变更</h4>
                  <div class="image-comparison">
                    <div class="current-images">
                      <h5>当前保留图片：</h5>
                      <div class="image-grid">
                        <el-image v-for="(url, index) in (currentRequest.request_data?.current_images || [])"
                          :key="`retain_${index}`" :src="getImageUrl(url)"
                          :preview-src-list="(currentRequest.request_data?.current_images || []).map(getImageUrl)" fit="cover"
                          style="width: 100px; height: 100px; margin: 5px;" />
                        <div v-if="(currentRequest.request_data?.current_images || []).length === 0" class="no-images">
                          无保留图片
                        </div>
                      </div>
                    </div>
                    <div class="new-images">
                      <h5>新增图片：</h5>
                      <div class="image-grid">
                        <el-image v-for="(url, index) in (currentRequest.request_data?.new_images || [])"
                          :key="`new_${index}`" :src="getImageUrl(url)"
                          :preview-src-list="(currentRequest.request_data?.new_images || []).map(getImageUrl)" fit="cover"
                          style="width: 100px; height: 100px; margin: 5px;" />
                        <div v-if="(currentRequest.request_data?.new_images || []).length === 0" class="no-images">
                          无新增图片
                        </div>
                      </div>
                    </div>
                  </div>
                  <div class="image-summary">
                    <p><strong>原图片数量：</strong>{{ (currentRequest.current_data?.image_urls || []).length }} 张</p>
                    <p><strong>保留图片：</strong>{{ (currentRequest.request_data?.current_images || []).length }} 张</p>
                    <p><strong>新增图片：</strong>{{ (currentRequest.request_data?.new_images || []).length }} 张</p>
                    <p><strong>最终图片数量：</strong>{{ getTotalImageCount(currentRequest) }} 张</p>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 审批信息 -->
        <div v-if="currentRequest.status !== 'pending'" class="detail-section">
          <h3>审批信息</h3>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="审批时间">
              {{ currentRequest.processed_at ? formatDate(currentRequest.processed_at) : '无' }}
            </el-descriptions-item>
            <el-descriptions-item label="审批意见">
              {{ currentRequest.admin_comment || '无' }}
            </el-descriptions-item>
          </el-descriptions>
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
          <el-button v-if="currentRequest?.status === 'pending'" type="success" @click="handleApprove(currentRequest)">
            批准申请
          </el-button>
          <el-button v-if="currentRequest?.status === 'pending'" type="danger" @click="handleReject(currentRequest)">
            拒绝申请
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 审批对话框 -->
    <el-dialog v-model="processDialogVisible" :title="processAction === 'approve' ? '批准申请' : '拒绝申请'" width="500px"
      :close-on-click-modal="false">
      <div class="process-form">
        <el-form ref="processFormRef" :model="processForm" label-width="100px">
          <el-form-item label="审批意见">
            <el-input v-model="processForm.admin_comment" type="textarea" :rows="4"
              :placeholder="processAction === 'approve' ? '请输入批准意见（可选）' : '请输入拒绝原因'" />
          </el-form-item>
        </el-form>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="processDialogVisible = false">取消</el-button>
          <el-button :type="processAction === 'approve' ? 'success' : 'danger'" :loading="processLoading"
            @click="confirmProcess">
            {{ processAction === 'approve' ? '确认批准' : '确认拒绝' }}
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 图片预览组件 -->
    <el-image-viewer
      v-if="imageViewerVisible"
      :url-list="previewUrls"
      :z-index="3000"
      :hide-on-click-modal="true"
      @close="closeImageViewer"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Search, View, Check, Close, ArrowRight } from '@element-plus/icons-vue'
import type { FormInstance } from 'element-plus'
import {
  getAllChangeRequests,
  processChangeRequest,
  type ChangeRequest
} from '@/api/changeRequest'
import { API_CONFIG } from '@/config'

// 响应式数据
const loading = ref(false)
const processLoading = ref(false)
const tableData = ref<ChangeRequest[]>([])
const detailDialogVisible = ref(false)
const processDialogVisible = ref(false)
const currentRequest = ref<ChangeRequest | null>(null)
const processAction = ref<'approve' | 'reject'>('approve')

// 搜索表单
const searchForm = reactive({
  parking_lot_name: '',
  status: '',
  request_type: ''
})

// 分页数据
const pagination = reactive({
  page: 1,
  pageSize: 10,
  total: 0
})

// 审批表单
const processFormRef = ref<FormInstance>()
const processForm = reactive({
  admin_comment: ''
})

// 方法定义
/**
 * 获取申请类型标签类型
 */
function getRequestTypeTagType(type: string): string {
  const typeMap: Record<string, string> = {
    'close_dates': 'warning',
    'activate': 'success',
    'modify_comprehensive': 'primary',
    'modify_spaces': 'primary',
    'modify_images': 'success',
    'modify_info': 'info'
  }
  return typeMap[type] || 'info'
}

/**
 * 获取申请类型文本
 */
function getRequestTypeText(type: string): string {
  const textMap: Record<string, string> = {
    'close_dates': '停用申请',
    'activate': '启用申请',
    'modify_comprehensive': '停车场信息编辑',
    'modify_spaces': '修改车位数',
    'modify_images': '修改图片',
    'modify_info': '修改信息'
  }
  return textMap[type] || '未知'
}

/**
 * 获取状态标签类型
 */
function getStatusTagType(status: string): string {
  const typeMap: Record<string, string> = {
    'pending': 'warning',
    'approved': 'success',
    'rejected': 'danger'
  }
  return typeMap[status] || 'info'
}

/**
 * 获取状态文本
 */
function getStatusText(status: string): string {
  const textMap: Record<string, string> = {
    'pending': '待处理',
    'approved': '已批准',
    'rejected': '已拒绝'
  }
  return textMap[status] || '未知'
}

/**
 * 格式化日期
 */
function formatDate(dateString: string): string {
  try {
    const date = new Date(dateString)
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit'
    })
  } catch (error) {
    return '格式错误'
  }
}

/**
 * 获取图片完整URL
 */
function getImageUrl(url: string): string {
  if (!url) return ''
  if (url.startsWith('http')) return url
  
  // 如果已经包含uploads路径，直接拼接服务器地址
  if (url.includes('/uploads/')) {
    return `${API_CONFIG.SERVER_URL}${url.startsWith('/') ? url : '/' + url}`
  }
  
  // 如果只是文件名，拼接完整的uploads路径
  const fileName = url.startsWith('/') ? url.substring(1) : url
  return `${API_CONFIG.UPLOADS_BASE_URL}/images/${fileName}`
}

/**
 * 检查字段是否有变化
 */
function hasFieldChange(request: ChangeRequest, field: string): boolean {
  const currentValue = request.current_data?.[field]
  const newValue = request.request_data?.[field]
  return currentValue !== newValue && newValue !== undefined
}

/**
 * 检查基本信息是否有变化
 */
function hasBasicInfoChanges(request: ChangeRequest): boolean {
  return hasFieldChange(request, 'name') ||
         hasFieldChange(request, 'contact_phone') ||
         hasFieldChange(request, 'backup_phone') ||
         hasFieldChange(request, 'address') ||
         hasFieldChange(request, 'description')
}

/**
 * 检查距离信息是否有变化
 */
function hasDistanceInfoChanges(request: ChangeRequest): boolean {
  return hasFieldChange(request, 'airport_distance_km') ||
         hasFieldChange(request, 'station_distance_km') ||
         hasFieldChange(request, 'shuttle_time_minutes')
}

/**
 * 检查服务设施是否有变化
 */
function hasServiceFacilitiesChanges(request: ChangeRequest): boolean {
  const currentFacilities = JSON.stringify(request.current_data?.service_facilities || [])
  const newFacilities = JSON.stringify(request.request_data?.service_facilities || [])
  return currentFacilities !== newFacilities
}

/**
 * 获取设施名称列表
 */
function getFacilityNames(facilities: string[]): string[] {
  const facilityMap: Record<string, string> = {
    'has_charging_pile': '充电桩',
    'is_24_hours': '24小时',
    'has_camera': '监控',
    'is_indoor': '室内',
    'has_24h_shuttle': '24H接送',
    'has_staff_on_duty': '专人值守',
    'has_surveillance': '监控',
    'has_7_seat_shuttle': '7座接送',
    'has_5_seat_shuttle': '5座接送',
    'has_parking_invoice': '发票',
    'walking_distance': '步行即达'
  }
  
  return facilities.map(key => facilityMap[key] || key).filter(Boolean)
}

/**
 * 检查图片是否有变化
 */
function hasImageChanges(request: ChangeRequest): boolean {
  const currentImageCount = (request.current_data?.image_urls || []).length
  const retainedImageCount = (request.request_data?.current_images || []).length
  const newImageCount = (request.request_data?.new_images || []).length
  
  // 有新增图片或删除了原有图片
  return newImageCount > 0 || retainedImageCount !== currentImageCount
}

/**
 * 获取最终图片总数
 */
function getTotalImageCount(request: ChangeRequest): number {
  const retainedCount = (request.request_data?.current_images || []).length
  const newCount = (request.request_data?.new_images || []).length
  return retainedCount + newCount
}

/**
 * 获取分类名称
 */
function getCategoryName(categoryId: number | null | undefined): string {
  if (!categoryId) return '未分类'
  // 这里应该从分类列表中获取名称，暂时显示ID
  // TODO: 需要加载分类数据
  return `分类${categoryId}`
}

/**
 * 检查价格规则是否有变化
 */
function hasPriceRulesChanges(request: ChangeRequest): boolean {
  const currentPriceRules = JSON.stringify(request.current_data?.price_rules || {})
  const newPriceRules = JSON.stringify(request.request_data?.price_rules || {})
  return currentPriceRules !== newPriceRules
}

/**
 * 格式化价格规则为文本显示
 */
function formatPriceRules(priceRules: any): string {
  if (!priceRules) return '未设置'
  
  const mode = priceRules.type === 'rolling_24h' ? '24小时计费' : '自然天计费'
  const indoorOutdoor = priceRules.indoor_outdoor_enabled ? '，启用室内外分别定价' : ''
  
  return `${mode}${indoorOutdoor}`
}

/**
 * 获取计费模式文本
 */
function getPricingModeText(type: string): string {
  return type === 'rolling_24h' ? '24小时计费' : '自然天计费'
}

/**
 * 获取每日价格对比数据
 */
function getDailyPricesComparison(request: ChangeRequest): any[] {
  const oldPrices = request.current_data?.price_rules?.daily_prices || {}
  const newPrices = request.request_data?.price_rules?.daily_prices || {}
  
  const comparison = []
  for (let i = 1; i <= 7; i++) {
    const oldPrice = oldPrices[`day_${i}`] || 0
    const newPrice = newPrices[`day_${i}`] || 0
    const diff = newPrice - oldPrice
    
    let change = '无变化'
    let changeClass = 'no-change'
    
    if (diff > 0) {
      change = `+${diff}元`
      changeClass = 'price-increase'
    } else if (diff < 0) {
      change = `${diff}元`
      changeClass = 'price-decrease'
    }
    
    comparison.push({
      day: `第${i}天`,
      oldPrice,
      newPrice,
      change,
      changeClass
    })
  }
  
  return comparison
}

/**
 * 检查营业资料是否有变化
 */
function hasBusinessDocumentsChanges(request: ChangeRequest): boolean {
  const currentBusinessDocs = JSON.stringify(request.current_data?.business_documents || {})
  const newBusinessDocs = JSON.stringify(request.request_data?.business_documents || {})
  return currentBusinessDocs !== newBusinessDocs
}

// 图片预览相关
const imageViewerVisible = ref(false)
const previewUrls = ref<string[]>([])

/**
 * 预览文档
 */
function previewDocument(url: string): void {
  if (!url) return
  
  // 构建完整的文件URL，使用和getImageUrl相同的逻辑
  const fullUrl = getImageUrl(url)
  
  // 判断文件类型
  const fileExtension = url.toLowerCase().split('.').pop()
  const imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp']
  
  if (imageExtensions.includes(fileExtension || '')) {
    // 图片类型使用图片预览
    previewUrls.value = [fullUrl]
    imageViewerVisible.value = true
  } else {
    // 其他文件类型在新窗口打开
    window.open(fullUrl, '_blank')
  }
}

/**
 * 关闭图片预览
 */
function closeImageViewer(): void {
  imageViewerVisible.value = false
  previewUrls.value = []
}

/**
 * 加载申请列表
 */
async function loadChangeRequests() {
  try {
    loading.value = true

    const params = {
      page: pagination.page,
      limit: pagination.pageSize,
      parking_lot_name: searchForm.parking_lot_name.trim() || undefined,
      status: searchForm.status || undefined,
      request_type: searchForm.request_type || undefined
    }

    const response = await getAllChangeRequests(params)

    if (response.success) {
      tableData.value = response.data.list
      pagination.total = response.data.total
    }
  } catch (error) {
    console.error('加载申请列表失败:', error)
    ElMessage.error('加载数据失败')
  } finally {
    loading.value = false
  }
}

/**
 * 搜索处理
 */
function handleSearch() {
  pagination.page = 1
  loadChangeRequests()
}

/**
 * 分页大小改变
 */
function handleSizeChange(size: number) {
  pagination.pageSize = size
  pagination.page = 1
  loadChangeRequests()
}

/**
 * 当前页改变
 */
function handleCurrentChange(page: number) {
  pagination.page = page
  loadChangeRequests()
}

/**
 * 查看申请详情
 */
function handleView(row: ChangeRequest) {
  currentRequest.value = row
  detailDialogVisible.value = true
}

/**
 * 批准申请
 */
function handleApprove(row: ChangeRequest) {
  currentRequest.value = row
  processAction.value = 'approve'
  processForm.admin_comment = ''
  processDialogVisible.value = true
}

/**
 * 拒绝申请
 */
function handleReject(row: ChangeRequest) {
  currentRequest.value = row
  processAction.value = 'reject'
  processForm.admin_comment = ''
  processDialogVisible.value = true
}

/**
 * 确认审批
 */
async function confirmProcess() {
  if (!currentRequest.value) return

  try {
    processLoading.value = true

    const response = await processChangeRequest(currentRequest.value.id, {
      action: processAction.value,
      admin_comment: processForm.admin_comment
    })

    if (response.success) {
      ElMessage.success(response.message)
      processDialogVisible.value = false
      detailDialogVisible.value = false
      loadChangeRequests()
    } else {
      ElMessage.error(response.message || '操作失败')
    }
  } catch (error) {
    console.error('审批失败:', error)
    ElMessage.error('操作失败')
  } finally {
    processLoading.value = false
  }
}

// 初始化
onMounted(() => {
  loadChangeRequests()
})
</script>

<style scoped>
.change-request-management {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h1 {
  margin: 0 0 8px 0;
  font-size: 24px;
  font-weight: 600;
}

.page-header p {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.operation-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 8px;
}

.search-area {
  display: flex;
  align-items: center;
}

.table-card {
  margin-bottom: 20px;
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.text-gray {
  color: #999;
}

.text-xs {
  font-size: 12px;
}

.request-detail {
  max-height: 600px;
  overflow-y: auto;
}

.detail-section {
  margin-bottom: 24px;
}

.detail-section h3 {
  margin: 0 0 16px 0;
  font-size: 16px;
  font-weight: 600;
  color: #333;
  border-bottom: 1px solid #eee;
  padding-bottom: 8px;
}

.reason-content {
  padding: 12px;
  background: #f8f9fa;
  border-radius: 4px;
  min-height: 60px;
  white-space: pre-wrap;
}

.change-content {
  padding: 12px;
  background: #f8f9fa;
  border-radius: 4px;
}

.image-comparison {
  display: flex;
  gap: 20px;
}

.current-images,
.new-images {
  flex: 1;
}

.image-grid {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.change-item {
  display: flex;
  align-items: center;
  gap: 12px;
}

.old-value {
  color: #999;
  text-decoration: line-through;
}

.new-value {
  color: #409eff;
  font-weight: 500;
}

.arrow-icon {
  color: #409eff;
}

.process-form {
  padding: 20px 0;
}

/* 统一编辑申请样式 */
.comprehensive-changes {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.change-section {
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  padding: 16px;
  background: #fafafa;
}

.change-section h4 {
  margin: 0 0 16px 0;
  font-size: 16px;
  font-weight: 600;
  color: #409eff;
  border-bottom: 2px solid #409eff;
  padding-bottom: 8px;
}

.change-section h5 {
  margin: 0 0 12px 0;
  font-size: 14px;
  font-weight: 600;
  color: #606266;
}

.no-images {
  color: #909399;
  font-style: italic;
  padding: 20px;
  text-align: center;
  background: #f5f7fa;
  border-radius: 4px;
  border: 1px dashed #d3d7de;
}

.image-summary {
  margin-top: 16px;
  padding: 12px;
  background: #f0f9ff;
  border-radius: 4px;
  border-left: 4px solid #409eff;
}

.image-summary p {
  margin: 4px 0;
  font-size: 14px;
  color: #606266;
}

/* 设施标签样式 */
.facilities-comparison {
  display: flex;
  gap: 20px;
  margin-top: 10px;
}

.old-facilities,
.new-facilities {
  flex: 1;
}

.old-facilities h5,
.new-facilities h5 {
  margin: 0 0 8px 0;
  font-size: 14px;
  font-weight: bold;
}

.facility-tags {
  min-height: 40px;
  padding: 8px;
  background: #f8f9fa;
  border-radius: 4px;
  border: 1px solid #e9ecef;
}

.no-facilities {
  color: #999;
  font-style: italic;
}

/* 价格规则样式 */
.price-rules-comparison {
  display: flex;
  align-items: center;
  gap: 16px;
  margin-bottom: 20px;
}

.old-price-rules,
.new-price-rules {
  flex: 1;
  padding: 12px;
  background: #f8f9fa;
  border-radius: 6px;
}

.price-rules-display {
  font-size: 14px;
  color: #606266;
  margin-top: 8px;
}

.detailed-price-comparison {
  margin-top: 20px;
}

.daily-prices-comparison {
  margin: 16px 0;
}

.daily-prices-comparison h6 {
  margin: 0 0 12px 0;
  font-size: 14px;
  font-weight: 600;
  color: #606266;
}

.price-increase {
  color: #F56C6C !important;
  font-weight: 600;
}

.price-decrease {
  color: #67C23A !important;
  font-weight: 600;
}

.no-change {
  color: #909399;
}

/* 营业资料样式 */
.business-document-section {
  margin-bottom: 24px;
  padding: 16px;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  background: #fafafa;
}

.business-document-section h5 {
  margin: 0 0 12px 0;
  font-size: 14px;
  font-weight: 600;
  color: #409eff;
}

.document-comparison {
  display: flex;
  align-items: flex-start;
  gap: 16px;
}

.old-documents,
.new-documents {
  flex: 1;
  padding: 12px;
  background: #f8f9fa;
  border-radius: 6px;
  min-height: 80px;
}

.old-documents h6,
.new-documents h6 {
  margin: 0 0 8px 0;
  font-size: 12px;
  color: #909399;
}

.document-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 8px;
  background: white;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  margin-bottom: 8px;
}

.document-name {
  flex: 1;
  font-size: 12px;
  color: #606266;
  margin-right: 8px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.no-documents {
  color: #909399;
  font-style: italic;
  text-align: center;
  padding: 20px;
  font-size: 12px;
}

.arrow-separator {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 32px;
}
</style>